<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="交易订单" prop="tradeOrderNo">
            <el-input v-model="queryParams.tradeOrderNo" placeholder="请输入交易订单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="商家名称" prop="merchantName">
            <el-input v-model="queryParams.merchantName" placeholder="请输入商家名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="店铺名称" prop="shopName">
            <el-input v-model="queryParams.shopName" placeholder="请输入店铺名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="订单金额" prop="amount">
            <el-input v-model="queryParams.amount" placeholder="请输入订单金额" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="收银账号" prop="cashier">
            <el-input v-model="queryParams.cashier" placeholder="请输入收银员" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            刷新间隔：
            <el-select placeholder="请选择刷新间隔时间" v-model="refreshTimes" @change="refreshQueryTimer">
              <el-option key="0" label="停止刷新" value="0" />
              <el-option key="10000" label="10秒" value="10000" />
              <el-option key="20000" label="20秒" value="20000" />
              <el-option key="30000" label="30秒" value="30000" />
            </el-select>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="payOrderList" class="tableEmpty">
        <el-table-column label="订单号/渠道订单" align="center" prop="orderNo" width="200px">
          <template #default="scope">
            <div style="color: #1c84c6">{{ scope.row.orderNo }}</div>
            <div style="color: #1ab394">{{ scope.row.tradeOrderNo }}</div>
          </template>
        </el-table-column>
        <el-table-column label="商户名称" align="center" prop="merchantName" />
        <el-table-column label="店铺名称" align="center" prop="shopName" />
        <el-table-column label="销售名称" align="center" prop="sellerName" />
        <el-table-column label="订单金额" align="center" prop="amount">
          <template #default="scope">
            <span><el-link type="warning">{{ scope.row.amount/100 }}</el-link></span>
          </template>
        </el-table-column>
        <el-table-column label="实付金额" align="center" prop="actualAmount">
          <template #default="scope">
            <span>{{ scope.row.actualAmount/100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原金额" align="center" prop="originalAmount">
          <template #default="scope">
            <span>{{ scope.row.originalAmount/100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收银员" align="center" prop="cashier" />
        <el-table-column label="付款人" align="center" prop="purchaser" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <span>
              <dict-tag :options="biz_pay_order_state" :value="scope.row.status" />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160px">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleNotify(scope.row)" v-hasPermi="['mall:payOrder:list']">已付款通知</el-button>
            <el-tooltip content="订单取消" placement="top" v-if="scope.row.status==1 && scope.row.accountingMode==1">
              <el-button link type="danger" @click="handleReverse(scope.row)" v-hasPermi="['mall:payOrder:list']">订单取消</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-dialog :title="securityDialog.title" v-model="securityDialog.visible" :show-close="false" :close-on-click-modal="false" width="500px" append-to-body>
      <el-card>
        <span>
          谷歌验证码:
          <el-input v-model="googleAuthCode" placeholder="请输入谷歌驗證碼" clearable style="width: 240px" />
        </span>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="doReverse">冲正提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PayOrder" lang="ts">
import {listPayOrder, paidNotify, reversePayOrder} from '@/api/promotor/payOrder';
import { PayOrderVO, PayOrderQuery, PayOrderForm } from '@/api/retail/payOrder/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { biz_pay_order_state } = toRefs<any>(proxy?.useDict("biz_pay_order_state"));

const payOrderList = ref<PayOrderVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const size = ref('')
const timer = ref<any>();
const refreshTimes = ref();
const queryFormRef = ref<ElFormInstance>();

const buttonLoading = ref(false);
const googleAuthCode = ref('');
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const securityDialog = reactive<DialogOption>({
  visible: false,
  title: '订单取消',
});
const initFormData: PayOrderForm = {
  id: undefined,
  orderNo: undefined,
  merchant: undefined,
  merchantName: undefined,
  shop: undefined,
  shopName: undefined,
  purchaser: undefined,
  amount: undefined,
  actualAmount: undefined,
  fee: undefined,
  cashier: undefined,
  cashBoxLink: undefined,
  shopProfit: undefined,
  merchantProfit: undefined,
  status: undefined,
}
const data = reactive<PageData<PayOrderForm, PayOrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    merchant: undefined,
    merchantName: undefined,
    shop: undefined,
    shopName: undefined,
    purchaser: undefined,
    amount: undefined,
    actualAmount: undefined,
    fee: undefined,
    cashier: undefined,
    cashBoxLink: undefined,
    shopProfit: undefined,
    merchantProfit: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
  }
});
const selectedRow = ref<{id:string|number|undefined,
  orderNo:string|undefined,status:string|number|undefined}>({
  id: 0,
  orderNo: '',
  status: 0
});
const { queryParams, form, rules } = toRefs(data);
/** 查询支付订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPayOrder(queryParams.value);
  payOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 冲正 **/
const handleReverse = async (row?: PayOrderVO) => {
  securityDialog.visible = true;
  selectedRow.value.id = row?.id;
  selectedRow.value.orderNo = row?.orderNo;
  selectedRow.value.status = row?.status;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 已收款通知 */
const handleNotify = async (row?: PayOrderVO) => {
  await proxy?.$modal.confirm('确认要通知"' + row?.cashier + '"收银号确认收款？');
  loading.value = true;
  paidNotify(row?.orderNo).then(res=>{
    proxy?.$modal.msgSuccess("已发送通知");
    getList();
  }).finally(()=>{
    loading.value = false;
  })
}

/** 设定刷新定时器 */
const refreshQueryTimer = (value: number) => {
  refreshTimes.value = value;
  if(timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  if(value!=0) {
    timer.value = setInterval(() => {
      getList();
    }, value)
  }
}

const doReverse = async () => {
  if(!googleAuthCode.value) {
    proxy?.$modal.msgWarning("请输入谷歌验证码");
    return;
  }
  buttonLoading.value = true;
  const res = await reversePayOrder(selectedRow?.value.id, googleAuthCode.value).finally(()=>{
    buttonLoading.value = false;
  });

  if (res.code == 200) {
    proxy?.$modal.msgSuccess("订单冲正成功");
    securityDialog.visible = false;
    googleAuthCode.value = '';
    await getList();
  } else {
    proxy?.$modal.msgError("订单冲正失败:" + res.msg);
  }
}

onUnmounted(() => {
  if(timer.value) {
    clearInterval(timer.value);
  }
});

onMounted(() => {
  getList();
});
</script>
<style scoped>
.el-descriptions-item {
  width: 120px;
}
</style>
